package com.czk.day03.save;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.apache.commons.io.IOUtils;

import java.io.*;

/**
 * 保存流程图到客户端
 * @Author ChenZhangKun
 * @Date 2020/9/10 15:45
 */
public class QueryBpmnFile {
    public static void main(String[] args) throws IOException{
        // 方法一：activiti提供的api获取
        getByActiviti();
        // 方法二：利用jdbc对blob数据的获取并保存
        // io流的转换，commons-io可以解决io操作
    }
    public static void getByActiviti() throws IOException {
        // 得到processEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        // 得到部署相关的Service
        RepositoryService repositoryService = processEngine.getRepositoryService();
        // 得到查询器
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
        // 指定key
        ProcessDefinitionQuery holiday = processDefinitionQuery.processDefinitionKey("holiday")
                .orderByProcessDefinitionVersion()
                .desc();
        // 执行查询操作
        ProcessDefinition processDefinition = holiday.singleResult();
        // 得到部署id
        String deploymentId = processDefinition.getDeploymentId();
        // 得到blob数据,拿到文件信息
        // deploymentId部署id
        // processDefinition.getDiagramResourceName()获取图片资源名称
        InputStream picStream = repositoryService.getResourceAsStream(deploymentId, processDefinition.getDiagramResourceName());
        // processDefinition.getResourceName()获取bpmn的资源文件名称
        InputStream bpmnStream = repositoryService.getResourceAsStream(deploymentId, processDefinition.getResourceName());
        // 构造输出流
        OutputStream picOutputStream=new FileOutputStream("D:\\czk\\pic\\"+processDefinition.getDiagramResourceName());
        OutputStream bpmnOutputStream=new FileOutputStream("D:\\czk\\pic\\"+processDefinition.getResourceName());
        // commonIo操作
        IOUtils.copy(picStream,picOutputStream);
        IOUtils.copy(bpmnStream,bpmnOutputStream);
        // 关闭流
        picStream.close();
        bpmnStream.close();
        picOutputStream.close();
        bpmnOutputStream.close();
        System.out.println("操作完成");
    }
}
